<template>
	<view class="content">
		<view class="box">
			<view v-show="create_show">
				<view class="search_title">
					<img src="../../static/image/home_icon_dayin@2x.png" alt="">
					<view>
						已连接到的打印设备
					</view>
				</view>
				<view class="created_device_box" v-show="created_device_show">
					<view class="created_device">
						<text class="created_device_name">{{device_name}}</text>
						<view class="state_box">
							<view class="circle"></view>
							<text class="state">已连接</text>
						</view>
					</view>
					<img src="../../static/image/home_icon_delete@2x.png" alt="" @click="delete_device">
				</view>
				<!-- 不删除已连接的设备 -->
				<view @click="search_again" class="search_loading" v-show="!search_show">重新搜索</view>
			</view>
			<view v-show="search_show">
				<view class="search_title">
					<img src="../../static/image/home_icon_dayin@2x.png" alt="">
					<view>
						搜索到的打印设备
					</view>
				</view>
				<view v-for="(item,index) in devices_list" v-if="(item.name !== '未知设备') && (item.name !== device_name)" class="device_list">
					<text class="device_name">{{item.name}}</text>
					<text @click="create_blue_tooth(item.deviceId,item.name)" class="create_btn">点击连接</text>
				</view>
				<view class="search_loading" v-show="loading">{{loading_text}}</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				token: '',
				loading: true,
				// 搜索到的设备列表
				devices_list: [],
				// 设备id
				deviceId: '',
				device_name: '',
				notifyCharacteristicId: '',
				writeCharacteristicId: '',
				//连接状态
				search_show: true,
				create_show: false,
				device_uuid: '',
				created_device_show: true,
				loading_text: '搜索中...'
			}
		},
		onUnload() {
			uni.stopBluetoothDevicesDiscovery({
			  success: res => {
			    console.log(res)
				console.log('----停止搜索----')
			  }
			})
		},
		onLoad() {
			// token
			uni.getStorage({
				key: 'token',
				success: res => {
					this.token = res.data
				}
			})
			// 初始化蓝牙
			uni.openBluetoothAdapter({
				success: res => {
					// 成功后开始搜寻附近的蓝牙外围设备
					this.searchBluetoothDevice()
				},
				fail: res => {
					uni.showModal({
						title: '提示',
						content: '初始化蓝牙失败 ，请打开蓝牙与位置信息功能，检查是否允许微信访问位置信息后重试',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.switchTab({
									url: '../index/index'
								})
							}
						}
					});
				}
			})
		},
		methods: {
			// 重新搜索
			search_again () { 
				this.loading_text = '搜索中...'
				this.search_show = true
				this.create_show = true
				this.devices_list = []
				this.loading = true
				// 检查蓝牙适配器状态 正常的话重走搜索程序 未选择新设备时不断开已有连接
				uni.getBluetoothAdapterState({
					success: res => {
						if (!res.discovering && res.available) {
							console.log('----蓝牙适配器状态正常，未搜索----')
							this.searchBluetoothDevice()
						}
					}
				})
			},
			// 删除设备
			delete_device (){
				// 断开连接
				uni.closeBLEConnection({
					deviceId: this.deviceId,
					success: res => {
						this.$https.get(`api/mini_customer/v1/bluetooth_devices/list?token=${this.token}`)
						.then(res => {
							if (res.code == 200) {
								this.device_uuid = res.data.result[0].uuid
								this.$https.delete(`api/mini_customer/v1/bluetooth_devices/delete?uuid=${res.data.result[0].uuid}&token=${this.token}`)
								.then(res => {
									// 删除后 删除
									this.deviceId = ''
									this.device_name = ''
									this.device_uuid = ''
									this.created_device_show = false
								})
							}
						})
					}
				})
			},
			// 搜寻附近的蓝牙外围设备
			searchBluetoothDevice () {
				uni.startBluetoothDevicesDiscovery({
					success: res => {
						console.log('startBluetoothDevicesDiscovery'+res)
						// 成功后监听寻找到的新设备
						this.onBluetoothDeviceFound()
						// 成功后 等待30秒后停止搜索
					},
					fail: res => {
						uni.showModal({
							title: '提示',
							content: '搜寻蓝牙设备失败，请退出小程序后重试',
							showCancel: false
						});
					}
				})
			},
			// 监听寻找到新设备
			onBluetoothDeviceFound () {
				uni.onBluetoothDeviceFound((devices) => {
					console.log(devices)
					// 监听到一次 就获取一次蓝牙设备列表 实时更新
					this.getBluetoothDevices()
				})
			},
			//获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						console.log('获取蓝牙设备成功:' + res.errMsg);
						// 设备列表去重
						let arr = res.devices
						for(var i=0; i<arr.length; i++){
						    for(var j=i+1; j<arr.length; j++){
						        if(arr[i].deviceId==arr[j].deviceId){         
									//第一个等同于第二个，splice方法删除第二个
						            arr.splice(j,1);
						            j--;
						        }
						    }
						}
						this.devices_list = arr;
					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							uni.showModal({
								title: '提示',
								content: '获取蓝牙设备失败，请退出小程序后重试',
								showCancel: false
							});
						}
					}
				});
			},
			// 点击连接蓝牙
			create_blue_tooth (deviceId,deviceName) {
				this.deviceId = deviceId;
				this.device_name = deviceName;
				this.loading_text = '正在连接...'
				uni.createBLEConnection({
				    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				    deviceId,
				    success: res => {
				    console.log(res)
					if (res.errCode == 0) {
						// 上报已连接的设备
						this.$https.post(`api/mini_customer/v1/bluetooth_devices/add`,{
							token: this.token,
							name: deviceName,
							device_id: deviceId
						})
						.then( res => {
							this.loading = false
							// 停止搜索
							uni.stopBluetoothDevicesDiscovery({
							  success: res => {
							    console.log(res)
								this.deviceId = deviceId;
								uni.setStorage({
									key: 'last_device_id',
									data: deviceId
								})
								uni.setStorage({
									key: 'last_device_name',
									data: deviceName
								})
								this.create_show = true
								this.search_show = false
								// 停止loding
								this.loading_text = '搜索中...'
								this.created_device_show = true
								// 链接后随时监听onBLEConnectionStateChange回调事件，当蓝牙设备断开时按需执行重连操作 断开后返回数据
								this.onBLEConnectionStateChange();
								// 若对未连接的设备或已断开连接的设备调用数据读写操作的接口，会返回 10006 错误，建议进行重连操作
							  }
							})
						})
					}
				},
				fail: res => {
					// 连接失败弹出弹窗
					console.log(res)
					  uni.showModal({
					  	title: '提示',
						content: '不支持该打印机，请重启打印机或重新搜索！',
						showCancel: false
					  })
				  }
				})
			},
			// 监听onBLEConnectionStateChange回调事件，监听蓝牙链接状态 断开后返回数据
			onBLEConnectionStateChange () {
				uni.onBLEConnectionStateChange( res => {
					console.log(res)
					if (res.connected === false) {
						// 断开后 删除上次连接的蓝牙
						this.$https.get(`api/mini_customer/v1/bluetooth_devices/list?token=${this.token}`)
						.then(res => {
							console.log(res)
							if (res.code == 200) {
								if (res.data.result.length != 0) {
									// this.device_uuid = res.data.result[0].uuid
									if (this.device_uuid != ''){
										this.$https.delete(`api/mini_customer/v1/bluetooth_devices/delete?uuid=${res.data.result[0].uuid}&token=${this.token}`)
										.then(res => {
											// 删除后 删除
											this.deviceId = ''
											this.device_name = ''
											this.device_uuid = ''
											this.created_device_show = false
										})
									} else {
										// 删除后 删除
										this.deviceId = ''
										this.device_name = ''
										this.device_uuid = ''
										this.created_device_show = false
									}
								} else {
									this.deviceId = ''
									this.device_name = ''
									this.device_uuid = ''
									this.created_device_show = false
								}
							}
						})
					}
				})
			},
			// 获取服务id
			// getBLEDeviceServices (deviceId) {
			// 	console.log('进入服务')
			// 	uni.getBLEDeviceServices({
			// 	  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			//  	  deviceId: this.deviceId,
			//  	  success: res => {
			//  	    console.log('device services:', res.services)
			// 		// 选择下标为1的serviceID
			// 		this.serviceId = res.services[1].uuid
			// 		// 获取特征id
			// 		this.getBLEDeviceCharacteristics(deviceId,res.services[1].uuid)
			//  	  }
			//  	})
			// },
			//  // 获取特征id
		// 	getBLEDeviceCharacteristics(deviceId, serviceId){
		// 	 	console.log("进入特征");
		// 	 	uni.getBLEDeviceCharacteristics({
		// 	 		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
		// 	 		deviceId,
		// 	 		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		// 	 		serviceId,
		// 	 		success:(res) => {
		// 	 			console.log(res)
		// 				// 获取notifyid 写死
		// 	 			this.notifyCharacteristicId = res.characteristics[0].uuid;
		// 				// 获取写id
		// 	 			for (var i = 0; i < res.characteristics.length; i++) {
		// 	 				console.log('特征值：' + res.characteristics[i].uuid)
		// 	 				if (res.characteristics[i].properties.write) {
		// 	 					console.log("writeCharacteristicsId：", res.characteristics[i].uuid);
		// 	 					this.writeCharacteristicId = res.characteristics[i].uuid;
		// 	 				}
		// 	 			}
		// 				// 获取特征值成功 显示已添加的打印机模块 存储设备id服务id特征id 上报连接成功的设备
		// 				this.$https.post(`api/mini_customer/v1/bluetooth_devices/add`,{
		// 					token: this.token,
		// 					name: this.device_name,
		// 					device_id: deviceId
		// 				})
		// 				.then( res => {
		// 					// 上报成功 储存 添加
		// 					let data = {
		// 						deviceId: deviceId,
		// 						serviceId: serviceId,
		// 						deviceName: this.device_name,
		// 						notifyCharacteristicId: this.notifyCharacteristicId,
		// 						writeCharacteristicId: this.writeCharacteristicId
		// 					}
		// 					uni.setStorage({
		// 						key: 'device_data',
		// 						data: data,
		// 						success: res => {
		// 							this.create_show = true
		// 							this.search_show = false
		// 							// 停止loding
		// 						}
		// 					})
		// 				})
		// 	 		},
		// 	 		fail:(res) => {
		// 	 			console.log(res)
		// 				uni.showModal({
		// 					title:'提醒',
		// 					content:'获取特征失败，请尝试重新连接',
		// 					showCancel: false
		// 				})
		// 	 		}
		// 	 	})
		// 	},
		}
	}
</script>

<style>
	.content {
		height: 100%;
		width: 100%;
		overflow-x: hidden;
	}
	.box{
		width: calc(100% - 48rpx);
		margin-left: 24rpx;
		margin-top: 24rpx;
		background-color: #ffffff;
		border-radius: 12rpx;
		padding-bottom: 24rpx;
	}
	.search_title{
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333333;
		padding-top: 24rpx;
	}
	.search_title img{
		width: 40rpx;
		height: 40rpx;
		margin-left: 24rpx;
		margin-right: 12rpx;
	}
	.search_loading{
		width: calc(100% - 48rpx - 8rpx);
		margin-left: 24rpx;
		margin-top: 24rpx;
		border: 4rpx solid #D1E0DA;
		border-radius: 12rpx;
		text-align: center;
		line-height: 92rpx;
		color: #13A684;
		font-size: 24rpx;
	}
	.device_list{
		width: calc(100% - 48rpx);
		margin-left: 24rpx;
		margin-top: 24rpx;
		border-radius: 12rpx;
		font-size: 24rpx;
		color: #13A684;
		background-color: #D1E0DA;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.device_name{
		margin-left: 24rpx;
	}
	.create_btn{
		margin-right: 24rpx;
	}
	.created_device_box{
		width: calc(100% - 48rpx);
		margin-left: 24rpx;
		margin-top: 24rpx;
		height: 100rpx;
		background-color: #13A684;
		border-radius: 12rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.created_device{
		display: flex;
		margin-left: 24rpx;
	}
	.created_device_box img{
		width: 48rpx;
		height: 48rpx;
		margin-right: 24rpx;
	}
	.created_device_name{
		color: #ffffff;
		font-size: 24rpx;
		margin-right: 24rpx;
	}
	.circle{
		width: 8rpx;
		height: 8rpx;
		border-radius: 4rpx;
		background: #64fb43;
		margin-right:6rpx;
	}
	.state_box{
		display: flex;
		align-items: center;
	}
	.state{
		color: #64FB43;
		font-size: 20rpx;
	}
</style>
